<template>
  <!-- 登录页面的整体盒子 -->
  <div class="login-container">
    <!-- 登录的盒子 -->
    <div class="login-box">
      <!-- 标题的盒子 -->
      <div class="title-box"></div>
      <!-- 登录的表单区域 -->
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
        <el-form-item prop="username">
          <el-input
            prefix-icon="el-icon-user"
            placeholder="请输入用户名"
            v-model="loginForm.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            prefix-icon="el-icon-lock"
            placeholder="请输入密码"
            type="password"
            v-model="loginForm.password"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width:100%" @click="doLogin"
            >登录</el-button
          >
          <br />
          <el-link href="#/register">去注册</el-link>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      //登录表单数据
      loginForm: {
        username: "",
        password: ""
      },
      //登录表单验证
      loginRules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          {
            pattern: /^\w{6,15}$/,
            message: "用户名必须是6-15位的字母、数字",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          {
            pattern: /^\w{6,15}$/,
            message: "密码必须是6-15位的字母、数字",
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    doLogin() {
      //1.表单验证是否成功
      this.$refs.loginFormRef.validate(async valide =>{
        //1.1 成功，发送ajax
        if( valide ){
          const {data:res} = await this.$axios.post('/api/login',this.loginForm)
          if( res.code === 0){
            //(1)提示消息
            this.$message.success(res.message)
            //(2)提交token更新到vuex
            this.$store.commit('updateToken',res.token)
            //(3)跳转首页
            this.$router.push('/')
          }else{
            this.$message.warning(res.message)
          }
        }
      })
    }
  }
};
</script>

<style lang="less" scoped>
.login-container {
  background: url("@/assets/images/login_bg.jpg") center;
  background-size: cover;
  height: 100%;

  .login-box {
    width: 400px;
    height: 270px;
    background-color: #fff;
    border-radius: 3px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    padding: 0 30px;
    box-sizing: border-box;

    .title-box {
      height: 60px;
      background: url("@/assets/images/login_title.png") center no-repeat;
    }

    .btn-login {
      width: 100%;
    }
  }
}
</style>
